<?php


namespace app\api\service;



use app\api\model\MeetUserModel;
use app\common\library\Auth;
use app\common\model\User;
use fast\Random;

class Format
{
    public static function formatInput($list,$field = '')
    {
        $list_json = htmlspecialchars_decode($list);
        $list_array = json_decode($list_json,true);

        if(!is_array($list_array)){
            return $list;
        }
        //print_r($list_array);die();
        $ids_arr = [];
        foreach($list_array as $k=>$v){
            if(!empty($v['id'])){
                $ids_arr[$k] = self::regUser($v,$field);
            }
        }
        $ids_string = implode(',',$ids_arr);
        //echo $ids_string;
        return $ids_string;
    }

    public static function regUser($params,$field = '')
    {
        $user = User::where('wx_userid',$params['id'])->find();
        if(empty($user)){
            $is_leader = $field=='check_ids'?1:0;
            $is_issued = $field=='issued_ids'?1:0;
            $auth = Auth::instance();
            $ext = [
                'avatar' => $params['avatar'],
                'nickname' => $params['name'],
                'wx_userid' => $params['id'],
                'is_leader' => $is_leader,
                'is_issued' => $is_issued,
            ];
            $auth->register($params['id'],Random::alnum(),'','',$ext);
            $user = $auth->getUserinfo();
            $user_id =  $user['id'];
        }else{
            $user_id = $user['id'];
            $is_leader = $field=='check_ids'?1:0;
            $is_issued = $field=='issued_ids'?1:0;
            $user->is_leader = $is_leader;
            $user->is_issued = $is_issued;
            $user->save();
        }
        return $user_id;
    }

    public static function getUserById($ids)
    {
        if(empty($ids)){
            return [];
        }
        $ids_arr = explode(',',$ids);
        $users = MeetUserModel::where('id','in',$ids_arr)->field('wx_userid as id ,nickname as name,avatar')->select();
        return $users;
    }


    public static function getUserByWxid($ids)
    {
        if(empty($ids)){
            return [];
        }
        $ids_arr = explode(',',$ids);
        $users = MeetUserModel::where('wx_userid','in',$ids_arr)->field('id,wx_userid')->select();
        if($users){
            $users= array_column($users,'id');
            $ids = implode(',',$users);
            return $ids;
        }
        return $ids;
    }
}
